from scapy.all import *
import gmssl.sm3 as sm3
import time

from scapy.layers.inet import TCP, IP


def chk_sum(a):
    b = str(a)
    length = len(b)
    if len(b) % 2 != 0:
        b += "0"
    ans_list = []
    for i in range(int(len(b) / 2)):
        temp = b[i * 2:i * 2 + 2].encode('utf-8')

        ans_list.append(sm3.sm3_kdf(temp, 1))
    ans = ""
    for i in ans_list:
        for j in range(2):
            temp2 = str(i[j])

            table = ['a', 'b', 'c', 'd', 'e', 'f']
            if temp2 in table:
                temp2 = str(table.index(temp2))
            ans += temp2

    return ans


def get_ascii(a):
    ans = ""
    for i in range(len(a)):
        b = bin(int(str(ord(a[i])), 10))
        temp = 8 - len(b[2:])
        for j in range(temp):
            ans += '0'
        ans += b[2:]
    print(ans)
    return ans


def time_get(key):
    pool = ['000', '001', '010', '011', '100', '101', '110', '111']
    time_pool = [1, 2, 3, 4, 5, 6, 7, 8]
    aim = get_ascii(key)
    time_list = []
    if len(aim) % 3 == 0:
        for i in range(int(len(aim) / 3)):
            time_list.append(time_pool[pool.index(aim[i * 3:i * 3 + 3])])
        return time_list
    else:
        for i in range(3 - len(aim) % 3):
            aim += '0'
        for i in range(int(len(aim) / 3)):
            time_list.append(time_pool[pool.index(aim[i * 3:i * 3 + 3])])
        print(time_list)
        return time_list


def send_pkt(packet_num, pkt_list, pkt_end, key: str = "p"):
    if packet_num < int(len(key) * 8 / 3) + 2:
        print("信息长度过长，请减少信息长度或增加数据包的数量")
    else:
        time2 = time_get(key)
        for pkt in pkt_list:
            send(pkt, iface="Intel(R) Wireless-AC 9560 160MHz")
            if pkt_list.index(pkt) < len(time2):
                time.sleep(time2[pkt_list.index(pkt)])
            else:
                time.sleep(1)
        else:
            send(pkt_end, iface="Intel(R) Wireless-AC 9560 160MHz")
        # list.append(random.randint(1, 30) / 10)
